<template>
	<div class="app-container">
		<el-row>
			<el-col :span="24">
				<el-row class="mb10">
					<el-form v-model="queryParams" ref="queryForm" :inline="true" label-width="80px">
						<custom-form-item v-for="element in queryFields" v-model="queryParams[element.vModel]" :element="element"></custom-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
							<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
						</el-form-item>
					</el-form>
				</el-row>
				<el-row :gutter="20" class="mb8">
					<el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handlerAdd" v-hasPermi="['{perimisionPre}:add']">添加</el-button></el-col>
					<el-col :span="1.5">
						<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['{perimisionPre}:remove']">删除</el-button>
					</el-col>
				</el-row>
				<i-table :columns="columns" :list="list"  :options="options" @handleSelectionChange="handleSelectionChange">
					<el-table-column slot="operate" label="操作" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['{perimisionPre}:edit']">修改</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['{perimisionPre}:remove']">删除</el-button>
						</template>
					</el-table-column>
				</i-table>

				<pagination v-show="total > 0" :total="total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize" @pagination="getList" />
			</el-col>
		</el-row>
		<el-dialog v-dialog-drag :visible.sync="open" :title="title" :close-on-click-modal="false">
			<div style="overflow:hidden;">
                <el-form ref="myForm" :model="myForm" label-width="120px">
                    <custom-form-item v-for="element in formFields" v-model="myForm[element.vModel]" :element="element"></custom-form-item>
                </el-form>
            </div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm" size="small">确 定</el-button>
				<el-button @click="cancel" size="small">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
    list{upperDir},
    add{upperDir},
    update{upperDir},
    del{upperDir},
    one{upperDir},
    one{upperDir}ForEdit
} from '@/api/{module}/{dir}/{fileName}.js';
import { requestByUrl } from '@/utils/tools';
import {formCofig,formFields,tableColumns,tags,queryFields} from "./conf/config";
import { isNull } from '@/utils';
import CustomFormItem from "@/components/CustomFormItem"
export default {
	name: "{upperDir}",
	components:{
       CustomFormItem
    },
	data() {
        return {
            formCofig: this._.cloneDeep(formCofig),
            ids: [],
            total: 0,
            multiple: true,
            queryParams: {},
            open: false,
            pageParams: {
                pageNum: 1, // 页码
                pageSize: 10 // 单页条数
            },
            list: [],
            queryFields: this._.cloneDeep(queryFields),
            columns: this._.cloneDeep(tableColumns),
            // table 配置
            options: {
                height: 630,
                mutiSelect:true
            },
            title: '',
            formFields: this._.cloneDeep(formFields),
            myForm: {}
        };
    },
	created() {
		this.getList();
		this.initData();
	},

	methods: {
		initData() {
            this.queryFields.map(async element => {
                element.renderKey = +new Date()
                element.clearable = element.clearable != undefined ? element.clearable : true

                this.$set(this.queryParams, element.vModel, element.defaultValue);
            });

            this.formFields.map(async element=>{
                element.renderKey = +new Date()

                this.$set(this.myForm,element.vModel,element.defaultValue)
            })
        },
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id);
			this.multiple = !selection.length;
		},
		handlerAdd() {
			this.reset();
			this.open = true;
			this.title = '添加';
		},
		handleUpdate(row) {
			let vm = this;
			const id = row.id;
			this.reset();
			this.myForm.id = id
			this.open = true;
			this.title = '修改';
			one{upperDir}ForEdit(id).then(response => {
				let f = response.data;
				this.formFields.forEach(element => {
                    if (typeof f[element.vModel] == 'object' && f[element.vModel] != null) {
                      if (f[element.vModel] instanceof Array) {
                        let temp = [];
                        if (element.mapping.vType && element.mapping.vType == 'object-array') {
                          let k = element.mapping.vKey ? element.mapping.vKey : 'id'
                          f[element.vModel].map(i => {
                            temp.push(i[k])
                          })
                        } else {
                          temp = f[element.vModel]
                        }
                        vm.$set(vm.myForm, element.vModel, temp);
                      } else {
                        let k = element.mapping.vKey ? element.mapping.vKey : 'id'
                        vm.$set(vm.myForm, element.vModel, f[element.vModel][k]);
                      }
                    } else {
                      vm.$set(vm.myForm, element.vModel, f[element.vModel]);
                    }
                  })
			});
		},
		handleDelete(row) {
			const ids = row.id != undefined ? [row.id] : this.ids;

			this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
					let data = {
						ids: ids
					};
					return del{upperDir}(data);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				})
				.catch(() => {});
		},
		handleQuery() {
			this.pageParams.pageNum = 1;
			this.getList();
		},
		resetQuery() {
			this.resetForm('queryForm');
			this.queryFields.map(item => {
				this.queryParams[item.prop] = item.queryOptions.value;
			});
			this.handleQuery();
		},
		getList() {
			let data = {
				page: this.pageParams.pageNum,
				limit: this.pageParams.pageSize,
				_order: ['id']
			};
			let w = {};
			this.queryFields.forEach(ele => {
                let key = '';
            	if (!isNull(this.queryParams[ele.vModel])) {
            	    if (ele.qsFlag != undefined) {
            		    key = ele.vModel + ele.qsFlag
                    } else {
                        key = ele.vModel
                    }
                    w[key] = this.queryParams[ele.vModel]
                }
            });
			if (Object.keys(w).length > 0) {
				data['_where'] = w;
			}
			list{upperDir}(data).then(response => {
				this.list = response.data.lists;
				this.total = response.data.query.total;
			});
		},
		submitForm() {
			if (this.myForm.id != undefined) {
				update{upperDir}(this.myForm).then(response => {
					this.msgSuccess('修改成功');
					this.open = false;
					this.getList();
				});
			} else {
				add{upperDir}(this.myForm).then(response => {
					this.msgSuccess('新增成功');
					this.open = false;
					this.getList();
				});
			}
		},
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
        reset() {
            let vm = this
            let f = this._.cloneDeep(formFields)
            f.map(it => {
        	    this.$set(vm.myForm,it.vModel,it.defaultValue)
        	});
        	if (this.myForm['id'] != undefined) {
        	    this.myForm['id'] = undefined;
        	}
        	this.resetForm('form');
        }
	}
};
</script>

<style lang="sass" scoped></style>
